<?php
 
class DB_Functions {
 
    private $db;
    private $log;
 
    //put your code here
    // constructor
    function __construct() {
    	//require dirname(__FILE__) . '/KLogger.php';
    	include_once dirname(__FILE__) . '/KLogger.php';
    	$this->log   = KLogger::instance(dirname(__FILE__) . '/../log', KLogger::DEBUG);
    	$this->log->logInfo('Info Test');
    	
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }
 
    // destructor
    function __destruct() {
         
    }
 
    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($fullname, $email, $password, $nickname) {
    	$this->log->logInfo('storeUser start. fullname: ', $fullname);
    	$this->log->logInfo('storeUser start. email: ', $email);
    	$this->log->logInfo('storeUser start. password: ', $password);
    	$this->log->logInfo('storeUser start. nickname: ', $nickname);
        //$uuid = uniqid('', true);
        //$hash = $this->hashSSHA($password);
        //$encrypted_password = $hash["encrypted"]; // encrypted password
        //$salt = $hash["salt"]; // salt
        
        //Generate random salt
    	$salt = $this->generateRandomSalt();
    	$this->log->logInfo('random generated salt: ', $salt);
    	
    	//Get core salt from DB
    	$result_salt_core = mysql_query("select * from engine4_core_settings where name = 'core.secret'");
    	$result_salt_core = mysql_fetch_array($result_salt_core);
    	$salt_core = $result_salt_core['value'];
    	$this->log->logInfo('salt_core from db: ', $salt_core);
    	
    	$encryptedPassword = md5($salt_core.$password.$salt);
    	$this->log->logInfo('encryptedPassword: ', $encryptedPassword);
    	
    	$result = mysql_query("INSERT INTO engine4_users(email, username, enabled, verified, creation_date, modified_date, timezone, level_id, password, salt, displayname, creation_ip) VALUES('$email', '$nickname', '1', '1', NOW(), NOW(), 'America/Buenos_Aires', '4', '$encryptedPassword', '$salt', '$fullname', '')");
    	$this->log->logInfo('result do insert do usuario: ', $result);
        // check for successful store
        if ($result) {
            // get user details 
            //$uid = mysql_insert_id(); // last inserted id
            //$result = mysql_query("SELECT * FROM engine4_users WHERE uid = $uid");
        	$result = mysql_query("SELECT * FROM engine4_users WHERE email = '$email'");
            
            
            // return user details
            
            return mysql_fetch_array($result);
        } else {
            return false;
        }
    }
    
    public function updateInitialInfoUser($email, $sex, $weight, $height, $dateBirthday, $id) {
    	
    	$this->log->logInfo('updateInitialInfoUser start. id: ', $id);
    	$this->log->logInfo('updateInitialInfoUser start. email: ', $email);
    	$this->log->logInfo('updateInitialInfoUser start. sex: ', $sex);
    	$this->log->logInfo('updateInitialInfoUser start. weight: ', $weight);
    	$this->log->logInfo('updateInitialInfoUser start. height: ', $height);
    	$this->log->logInfo('updateInitialInfoUser start. dateBirthday: ', $dateBirthday);
    	
    	$result = mysql_query("SELECT * FROM runners_user_info WHERE user_id = '$id'");
    	
    	$this->log->logInfo('select result: ', $result);
    	if(mysql_fetch_array($result)) {
    		//if(mysql_fetch_array($result)) {
    		//TODO:acho que é essa linha de cima que ta cagada. acho que tinha que ser uma verif só de $result antes
    		//register exists. update
    		$strupdatelog = "a";
    		$this->log->logInfo('strupdatelog: ', $strupdatelog);
    		$result = mysql_query("UPDATE runners_user_info SET weight = $weight, height = $height 
    				WHERE user_id = '$id'");
    	} else {
    		$strupdatelog = "b";
    		$this->log->logInfo('strupdatelog: ', $strupdatelog);
    		//register do not exist. insert
    		$result = mysql_query("INSERT INTO runners_user_info (user_id, weight, height) 
    				VALUES($id, $weight, $height)");
    	}
//     	 else {
    		
//     	}
    	 
    	$this->log->logInfo('result do insert do usuario: ', $result);
    	// check for successful store
    	if ($result) {
    		
    		$result = mysql_query("SELECT * FROM runners_user_info WHERE user_id = '$id'");
    
    		//return user details
    		return mysql_fetch_array($result);
    	} else {
    		return false;
    	}
    }
    
    function generateRandomSalt() {
    	mt_srand(microtime(true)*100000 + memory_get_usage(true));
    	return md5(uniqid(mt_rand(), true));
    }
 
    /**
     * Get user by email and password
     */
    public function getUserByEmailAndPassword($email, $password) {
    	$this->log->logInfo('getUserByEmailAndPassword start. email: ', $email);
    	$this->log->logInfo('getUserByEmailAndPassword start. password: ', $password);
    	
        $result = mysql_query("SELECT * FROM engine4_users WHERE email = '$email'") or die(mysql_error());
        // check for result 
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
            $salt = $result['salt'];
            $this->log->logInfo('Salt from db: ', $salt);
            
            $encrypted_password = $result['password'];
            $this->log->logInfo('encrypted_password from db: ', $encrypted_password);
            
            
            
            $result_salt_core = mysql_query("select * from engine4_core_settings where name = 'core.secret'");
            $result_salt_core = mysql_fetch_array($result_salt_core);
            $salt_core = $result_salt_core['value'];
            
            $this->log->logInfo('salt_core from db: ', $salt_core);
            
            $encrypted_password_sent = md5($salt_core.$password.$salt);
            $this->log->logInfo('encrypted_password_sent: ', $encrypted_password_sent);
            
            if ($encrypted_password == $encrypted_password_sent) {
            	return $result;
            }
            		
//             $hash = $this->checkhashSSHA($salt, $password);
//             // check for password equality
//             if ($encrypted_password == $hash) {
//                 // user authentication details are correct
//                 return $result;
//             }
        } else {
            // user not found
            return false;
        }
    }
 
    /**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $result = mysql_query("SELECT email from engine4_users WHERE email = '$email'");
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed 
            return true;
        } else {
            // user not existed
            return false;
        }
    }
 
    /**
     * Encrypting password
     * @param password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) {
 
        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }
 
    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password) {
 
        $hash = base64_encode(sha1($password . $salt, true) . $salt);
 
        return $hash;
    }
 
}
 
?>